<?php

class ActivityController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column1';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('index', 'view', 'create', 'update', 'admin', 'delete','recommend','win','unwin','publish'),
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $search['username'] = trim($_REQUEST['username']);
        $search['code'] = trim($_REQUEST['code']);
        $condition = new CDbCriteria();
        $condition->with = 'user';
        if($search['username']){
            $condition->addCondition("user.username='".$search['username']."'");
        }
        if($search['code']){
            $condition->addCondition("t.code='".$search['code']."'");
        }
        $condition->addCondition('t.activityid='.(int)$id);
        $count = Record::model()->count($condition);
        $condition->order = 't.win desc,t.dateline desc';
        $pager = new CPagination($count);
        $pager->pageSize = 10;
        $pager->applyLimit($condition);
        $rowTable = Record::model()->findAll($condition);
        unset($condition);
       
        $this->render('view', array(
            'model' => $this->loadModel($id),
            'rowTable' => $rowTable,
            'pages' => $pager,
            'search' => $search,
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Activity;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Activity'])) {
            $model->attributes = $_POST['Activity'];
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->activityid));
        }
        $condition = new CDbCriteria();
        $condition->addCondition("status='正常'");
        $condition->order = 'hot desc';
        $prize = Prize::model()->findAll($condition);
        unset($condition);

        $this->render('create', array(
            'model' => $model,
            'prize' => $prize,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Activity'])) {
            $model->attributes = $_POST['Activity'];
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->activityid));
        }
        
        $condition = new CDbCriteria();
        $condition->addCondition("status='正常'");
        $condition->order = 'hot desc';
        $prize = Prize::model()->findAll($condition);
        unset($condition);

        $this->render('update', array(
            'model' => $model,
            'prize' => $prize,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
//        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
//        }
//        else
//            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $criteria = new CDbCriteria();

        //根據參數設置搜索條件
        $search['class'] = $_REQUEST['class'];
        $search['status'] = $_REQUEST['status'];
        $search['timetype'] = $_REQUEST['timetype'];
        $search['s'] = $_REQUEST['s'];
        $search['e'] = $_REQUEST['e'];
        $search['searchtype'] = $_REQUEST['searchtype'];
        $search['key'] = $_REQUEST['key'];
        if ($search['class']) {
            $criteria->addCondition("t.class='" . $search['class'] . "'");
        }
        if ($search['status']) {
            $criteria->addCondition('t.status=' . (int) $search['status']);
        }
        
        if ($search['s'] && $search['timetype']) {
            $criteria->addCondition("t.".$search['timetype'].">='" . $search['s'] . "'");
        }
        if ($search['e'] && $search['timetype']) {
            $criteria->addCondition("t.".$search['timetype']."<'" . $search['e'] . "'");
        }
        
        if ($search['searchtype'] && $search['key']) {
            $criteria->addCondition("t.".$search['searchtype']."='".$search['key']."'");
        }
        $criteria->order = 't.hot desc';
        $count = Activity::model()->count($criteria);
        $pager = new CPagination($count);
        $pager->pageSize = 10;
        $pager->applyLimit($criteria);
        $rowTable = Activity::model()->findAll($criteria);
        $this->render('index', array('rowTable' => $rowTable, 'pages' => $pager, 'search' => $search));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new Activity('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Activity']))
            $model->attributes = $_GET['Activity'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = Activity::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'activity-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
    
    //推薦
    public function actionRecommend(){
        $id = (int)$_POST['id'];
        $model = Activity::model()->findByPk($id);
        if($model){
            $model->recommend = $model->recommend?0:1;
            $model->save();
            $msg = '更新成功';
        }else{
            $msg = "ID錯誤，未找到記錄";
        }
        echo CJSON::encode(array('success' => true, 'msg' => $msg));
    }
    
    //設置為中獎
    public function actionWin(){
        $id = (int)$_POST['id'];
        $model = Record::model()->findByPk($id);
        if($model){
            //判斷當前的活動的中獎人數是否已滿
            $condition = new CDbCriteria();
            $condition->addCondition('win=1');
            $condition->addCondition('activityid='.$model->activityid);
            $count = Record::model()->count($condition);
            if($count<$model->activity->winner){
                $model->win = 1;
                $model->save();
                $msg = '更新成功';
            }else{
                $msg = '本活動的中獎人數已滿，如需設置本記錄為中獎，請先取消一個其他中獎記錄';
            }            
        }else{
            $msg = "ID錯誤，未找到記錄";
        }
        echo CJSON::encode(array('success' => true, 'msg' => $msg));
    }
    
    //取消中獎
    public function actionUnwin(){
        $id = (int)$_POST['id'];
        $model = Record::model()->findByPk($id);
        if($model){
            $model->win = 0;
            $model->save();
            $msg = '更新成功';
        }else{
            $msg = "ID錯誤，未找到記錄";
        }
        echo CJSON::encode(array('success' => true, 'msg' => $msg));
    }
    
    //活動開獎
    public function actionPublish(){
        $id = (int)$_POST['id'];
        $model = Activity::model()->findByPk($id);
        if($model){
            $model->status = 5;
            $model->endtime = date('Y-m-d H:i:s');
            $model->save();
            $msg = '更新成功';
        }else{
            $msg = "ID錯誤，未找到記錄";
        }
        echo CJSON::encode(array('success' => true, 'msg' => $msg));
    }

}
